package com.gujiangbo.multithreadskill;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author gujiangbo
 */
public class Sale_Tickets {
    public static void main(String[] args) {
        Sales sale = new Sales();
        Thread nanjing = new Thread(sale, "Nanjing");
        Thread shangHai = new Thread(sale, "ShangHai");
        Thread beijing = new Thread(sale, "BeiJing");
        nanjing.start();
        shangHai.start();
        beijing.start();
    }
}

class Sales implements Runnable {
    // private static AtomicInteger total_tickets = new AtomicInteger(50);
    private static int tickets = 50;
    Object o = new Object();

   /* public void run() {
        while (true) {
            if (total_tickets.get() > 0) {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在卖出第" + total_tickets.decrementAndGet() + "张票~");
            } else {
                break;
            }
        }
    }*/

    public void run() {

        synchronized (o) {
            while (true) {
                if (tickets > 0) {
                    try {
                        Thread.sleep(300);
                        System.out.println(Thread.currentThread().getName() + "正在卖出第" + tickets-- + "张票~");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }
}
